﻿using DataService.Core.Log;

namespace App.API.Security
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate next;
        public ExceptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next.Invoke(context);
            }
            catch (Exception e)
            {
                await HandleException(context, e);
            }
        }
        private async Task HandleException(HttpContext context, Exception e)
        {
            await Task.Run(() =>
            {
                TraceLog.WriteLine("异常中间件记录的错误：" + e.StackTrace + "***" + e.Message, "全局日志");
            });
            //LogTools.WriteLine("异常中间件记录的错误：" + e.StackTrace + "***" + e.Message, "全局日志");

            //if (!context.Response.HasStarted)
            //    context.Response.Headers.Add("Content-Type", "application/json; charset=utf-8");

            ////context.Response.ContentType = "application/json;charset=utf-8;";
            //int statusCode = 400;
            //HandleResult handleResult = new HandleResult { StatusCode = statusCode, Msg = "调用接口失败" };
            //LogTools.WriteLine("异常中间件记录的错误：" + e.StackTrace + "***" + e.Message, "全局日志");
            //string reponseResult = SerializationHelper.SerializeDataToJson(handleResult);

            //await context.Response.WriteAsync(reponseResult);
        }
    }
}
